package com.tian.arch.function.http

import android.annotation.SuppressLint
import android.net.SSLCertificateSocketFactory
import android.util.Log
import com.tian.arch.function.http.HttpsTrustManager
import java.lang.Exception
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*

class HttpsTrustManager : X509TrustManager {
    @SuppressLint("TrustAllX509TrustManager")
    override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
    }

    @SuppressLint("TrustAllX509TrustManager")
    override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
    }

    override fun getAcceptedIssuers(): Array<X509Certificate> {
        return arrayOf()
    }

    class TrustAllHostnameVerifier : HostnameVerifier {
        @SuppressLint("BadHostnameVerifier")
        override fun verify(s: String, sslSession: SSLSession): Boolean {
            return true
        }
    }

    companion object {
        fun createSSLSocketFactory(): SSLSocketFactory {
            var sSLSocketFactory: SSLSocketFactory
            try {
                val sc = SSLContext.getInstance("TLS")
                sc.init(
                    null, arrayOf<TrustManager>(HttpsTrustManager()),
                    SecureRandom()
                )
                sSLSocketFactory = sc.socketFactory
            } catch (e: Exception) {
                Log.e("error", e.message!!)
                sSLSocketFactory = SSLCertificateSocketFactory(1)
            }
            return sSLSocketFactory
        }
    }
}